package com.yitao.cms.utils;

import com.skipper.base.json.JSON;
import com.skipper.base.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * Function:
 * Date: 2018/12/21
 *
 * @author skipper
 * @desc
 * @see
 */
public class FileUtil {

    protected Logger logger = LoggerFactory.getLogger(getClass());


    private JSONObject loadFileReturnJsonObject(String fileName) {

        String data = loadFile(fileName);
        if (StringUtils.isEmpty(data)) {
            return JSON.parseObject(data);
        }
        return new JSONObject();
    }

    private String loadFile(String filePath) {
        logger.info("读取配置文件:{}", filePath);
        String data = "";
        try {
            File file = getFile(filePath);

            if (file.exists()) {
                    FileInputStream stream = new FileInputStream(file);
                    data = StreamUtils.copyToString(stream, StandardCharsets.UTF_8);
            } else {
                logger.info("找不到配置文件:{}", filePath);
            }
        } catch (Exception e) {
            logger.info("找不到配置文件:{}", filePath);
        }
        return data;
    }

    public File getFile(String filePath) {
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:"+ filePath);
        } catch (Exception e) {
        }
        try {
            if (file == null) {
                InputStream stream = getClass().getClassLoader().getResourceAsStream(filePath);
                file = new File(filePath);
                FileUtils.copyInputStreamToFile(stream, file);
            }
        } catch (Exception e) {
        }
        return file;
    }

    public static void main(String[] args) {
        FileUtil fileUtil = new FileUtil();
        System.out.println(fileUtil.loadFile("test.json"));
    }

}
